package cn.zust.ly.service.impl;


import cn.zust.ly.dao.hibernate.BaseDao;
import cn.zust.ly.dto.SessionInfo;
import cn.zust.ly.entity.Tuser;
import cn.zust.ly.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by liy on 2016/11/10.
 */
@Service
@Transactional
public class UserServiceImpl implements UserService {

    @Autowired
    private BaseDao<Tuser> userDao;


    @Override
    public Tuser getUserByLoginName(String username) {
        String hql = "from Tuser u where u.username = '" + username + "'";
        return userDao.get(hql);
    }

    @Override
    public List<Tuser> getAllUser() {
        String hql = "from Tuser where type=1";
        return userDao.find(hql);
    }


    @Override
    public boolean doLogin(String username, String pwd, HttpSession session) {
        String countHql = "select count(*) from Tuser u where u.username = '" + username + "'";
        if (userDao.count(countHql) == 0) return false;
        else {
            Tuser user = userDao.get("from Tuser u where u.username = '" + username  + "'");
            if (user.getPassword().equals(pwd)) {
               // user.setLastLoginTime(new Date());
                SessionInfo sessionInfo = new SessionInfo(user);
                session.setAttribute("sessionInfo", sessionInfo);
                userDao.update(user);
                return true;
            }
        }
        return false;
    }

    @Override
    public boolean doRegister(Tuser user) {
        try {
           // user.setType((short) 1);
            userDao.save(user);
        } catch (Exception e) {
            return false;
        }
        return true;
    }


}
